package com.compass.mobile.ui.dialog

import AppManager
import LogUtil
import android.annotation.SuppressLint
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import androidx.fragment.app.FragmentActivity
import androidx.leanback.widget.ArrayObjectAdapter
import androidx.leanback.widget.BaseGridView
import androidx.leanback.widget.FocusHighlight
import androidx.leanback.widget.FocusHighlightHelper
import com.compass.mobile.R
import com.compass.mobile.callback.OnItemClickListener
import com.compass.mobile.databinding.DialogInspectSelectedBinding
import com.compass.mobile.framework.base.BaseDialog
import com.compass.mobile.framework.base.BaseDialogFragment
import com.compass.mobile.framework.ext.onClick
import com.compass.mobile.framework.utils.dpToPx
import com.compass.mobile.models.IndependentBillingBean
import com.compass.mobile.presenters.SelectedInspectPresenter
import com.compass.mobile.callback.OnInspectCallBack
import com.compass.mobile.framework.constant.INSPECT_CONFIRM
import com.compass.mobile.framework.constant.YD_USER_TOKEN
import com.compass.mobile.framework.utils.BigDecimalUtils
import com.compass.mobile.framework.utils.CodeUtils.getCodeUrl
import com.compass.mobile.framework.utils.QRCodeDealUtils
import com.compass.mobile.widget.MyBridgeAdapter
import dp2px
import getStringFromResource
import toJson

/**
 * Description： 检验检测项目已选弹窗
 * Date:2024/6/8 12:16
 */
class InspectSelectedOrderDialog {
    class Builder(
        activity: FragmentActivity,
        private var selectedList: MutableList<IndependentBillingBean>,
        private var onInspectCallBack: OnInspectCallBack,

    ) :
        BaseDialogFragment.Builder<Builder>(activity) {
        private val onItemClickListener: OnItemClickListener = object : OnItemClickListener {
            override fun onItemClick(position: Int, view: View) {
                CommonMessageDialog.Builder(activity)
                    .setTitle("温馨提示")
                    .setMessage("确认要删除当前项目吗?")
                    .setConfirm(getStringFromResource(R.string.default_confirm))

                    .setCancel(getString(R.string.default_cancel))
                    .setonCancelListener {
                        it?.dismiss()
                    }
                    .setonConfirmListener {

                        if (::arrayObjectAdapter.isInitialized) {
                            arrayObjectAdapter.remove(selectedList[position])
                            selectedList.removeAt(position)
                        }

                        initMoneyView()

                        onInspectCallBack.onInspectCallBack("delete", selectedList)

                        it?.dismiss()
                    }.create().show()

            }
        }
        private val mBinding: DialogInspectSelectedBinding =
            DialogInspectSelectedBinding.inflate(LayoutInflater.from(activity))
        private lateinit var arrayObjectAdapter: ArrayObjectAdapter

        init {
            initView()
        }

        private fun initView() {
            setContentView(mBinding.root)
            setWidth((AppManager.getScreenHeightPx() * 0.9).toInt())
            setHeight((AppManager.getScreenWidthPx() * 0.8).toInt())
            setAnimStyle(BaseDialog.AnimStyle.DEFAULT)
            setGravity(Gravity.CENTER)
            setCancelable(true)
            specialColumn()

            mBinding.tClose.onClick {
                dismiss()
            }
//            mBinding.tvSubmit.onClick {
//                dismiss()
//                onInspectCallBack.onInspectCallBack("submit", selectedList)
//            }
            initMoneyView()
        }

        /**
         * 计算价格
          */
        private fun initMoneyView() {
            var drugsCost = "0"
            for (item in selectedList) {
                item.price.let {
                    drugsCost = BigDecimalUtils.add(it, drugsCost, 2)
                }
            }
            mBinding.tvTotal.text = "已选${selectedList.size}项 共计:￥${drugsCost}"
//            mBinding.tvMoney.text = "共计${drugsCost}"
            mBinding.ivCode.setImageBitmap(
                QRCodeDealUtils.generateQRCodeWithoutMarginBlack(
                    getCode(),
                    dp2px(300f),
                    dp2px(300f)
                )
            )
        }

        private fun getCode():String{

            val ids = ArrayList<String>()
            for (item in selectedList){
                ids.add(item.id)
            }
            val codeUrl =  "${INSPECT_CONFIRM}${getCodeUrl()}&ids=${ids.toJson()}"
            LogUtil.d("codeUrl = ${codeUrl}")
            return  codeUrl
        }

        @SuppressLint("RestrictedApi")
        fun specialColumn() {
            mBinding.caseItem.setNumColumns(1)
            mBinding.caseItem.horizontalSpacing = dpToPx(10)
            mBinding.caseItem.verticalSpacing = dpToPx(10)
            arrayObjectAdapter = ArrayObjectAdapter(SelectedInspectPresenter())
            val itemBridgeAdapter = MyBridgeAdapter(
                activity,
                arrayObjectAdapter, onItemClickListener
            )
            mBinding.caseItem.setAdapter(itemBridgeAdapter)
            mBinding.caseItem.setFocusScrollStrategy(BaseGridView.FOCUS_SCROLL_ITEM)
            arrayObjectAdapter.addAll(0, selectedList)
            FocusHighlightHelper.setupBrowseItemFocusHighlight(
                itemBridgeAdapter,
                FocusHighlight.ZOOM_FACTOR_NONE, false
            )
        }
    }
}